package com.mjk.manager.amis.core.controller;

import cn.hutool.core.util.StrUtil;
import com.mjk.common.base.constns.BeeCommonConstns;
import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.core.jdbc.service.idgenerator.IdGenerateType;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeComplexQueryWrapper;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.util.TreeUtils;
import com.mjk.manager.amis.core.dto.AmisCrudDTO;
import com.mjk.manager.amis.core.dto.RoleMenuDto;
import com.mjk.manager.amis.core.dto.SessionDetails;
import com.mjk.manager.amis.core.model.SysMenu;
import com.mjk.manager.amis.core.model.SysRoleMenu;
import com.mjk.manager.amis.core.utils.SessionHolder;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RequestMapping("/mamis/sys/menu")
@RestController
@Slf4j
public class SysMenuController {
	@Autowired
	SessionHolder contextService;

	@Autowired
    BeeDBService beeDBService;

	@GetMapping("/list")
	public BeeResponse getMenuList(final HttpServletRequest request) {
		String curSysId = contextService.getSystem(request).getId();
		if(ObjectUtils.isEmpty(curSysId)){
			return BeeError.TOKEN_IS_EXPRIE.tranceError();
		}
		// 查询数据库
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new SysMenu());

		List<SysMenu> menuList = beeDBService.findManyByWrapper(wrapper);
		List<SysMenu> menuTree = TreeUtils.list2Tree(menuList, "0", "id", "PID", "children", false);

		// 构造 amis 要求的数据结构
		final AmisCrudDTO<SysMenu> data = new AmisCrudDTO<>();
		data.setItems(menuTree);
		// data.setTotal(sysMenuMapper.selectCount(wrapper));

		// 返回结果集
		return BeeError.BEE_SUC.tranceError(data);
	}

	/**
	 * 角色对应的菜单
	 * @param roles
	 * @return
	 */
	@RequestMapping("roleMenus")
	public BeeResponse getMenuByRole(String roleId){
		BeeComplexQueryWrapper wrapper1 = new BeeComplexQueryWrapper(SysMenu.class,"a");
		wrapper1.innerJoin(SysRoleMenu.class,"b").on(SysMenu::getId,SysRoleMenu::getMENU_ID);
		wrapper1.eq(SysRoleMenu::getROLE_ID,"b", roleId);
		List<SysMenu> menus = beeDBService.findManyByComplexWrapper(wrapper1);
		return BeeError.BEE_SUC.tranceError(menus);
	}

	@RequestMapping("saveRoleMenus")
	public BeeResponse saveRoleMenu(@RequestBody RoleMenuDto dto){
		if(!CollectionUtils.isEmpty(dto.getMenuIds())){
			//先删除
			BeeQueryWrapper wrapper = new BeeQueryWrapper(SysRoleMenu.class);
			wrapper.eq(SysRoleMenu::getROLE_ID,dto.getRoleId());
			beeDBService.delete(wrapper);
			List<SysRoleMenu> roleMenus = new ArrayList<>();
			for(String menuId : dto.getMenuIds()){
				SysRoleMenu roleMenu = new SysRoleMenu();
				roleMenu.setROLE_ID(dto.getRoleId()).setMENU_ID(menuId).setId(IdGenerateType.AUTO_SNOWFLAKE.getGenerator().getId(roleMenu))
						.setDELETED(false).setCREATED_BY(dto.getCreater()).setCREATED_AT(LocalDateTime.now())
						.setUPDATED_BY(dto.getCreater()).setUPDATED_AT(LocalDateTime.now());
				roleMenus.add(roleMenu);
			}
			beeDBService.save(roleMenus);
		}
		return BeeError.BEE_SUC.tranceError();
	}

	@PostMapping(value = {"","save"})
	public BeeResponse saveMenu(final HttpServletRequest request, @RequestBody final SysMenu obj) {
		final SessionDetails session = contextService.getSession(request);
		if(session == null){
			return BeeError.TOKEN_IS_EXPRIE.tranceError();
		}
		final SysMenu entity = new SysMenu();

		// 设置更新人员
		entity.setUPDATED_BY(session.getCurUser().getId());

		int ret;
		if (StrUtil.isNotBlank(obj.getId())) {
			// update
			BeeQueryWrapper wrapper = new BeeQueryWrapper(obj);
			wrapper.eq(SysMenu::getId, obj.getId());
			ret = beeDBService.update(wrapper);
		} else {
			// insert
			// 设置创建人员
			entity.setDELETED(BeeCommonConstns.DEFAULT_UNDEL);
			entity.setId(IdGenerateType.AUTO_SNOWFLAKE.getGenerator().getId(entity));
			entity.setCREATED_BY(session.getCurUser().getId());
			entity.setCREATED_AT(LocalDateTime.now());
			entity.setUPDATED_AT(LocalDateTime.now());
			// 设置所属关系

			ret = beeDBService.save(entity);
		}
		return ret > 0 ? BeeError.BEE_SUC.tranceError() : BeeError.BEE_FAILD.tranceError();
	}

	@RequestMapping(value = {"/{id}","delete/{id}"})
	public BeeResponse delMenu(final HttpServletRequest request, @PathVariable("id") String id) {
		//SysMenu menu = new SysMenu();
		//menu.setDELETED(BeeCommonConstns.DEFAULT_DEL);
		BeeQueryWrapper wrapper = new BeeQueryWrapper(SysMenu.class);
		wrapper.in(SysMenu::getId, Arrays.asList(id.split(",")));
		int ret = beeDBService.delete(wrapper);
		return ret > 0 ? BeeError.BEE_SUC.tranceError() : BeeError.BEE_FAILD.tranceError();
	}

	@GetMapping("/option")
	public BeeResponse getMenuOptionList(final HttpServletRequest request) {
		String curSysId = contextService.getSystem(request).getId();
		if(ObjectUtils.isEmpty(curSysId)){
			return BeeError.TOKEN_IS_EXPRIE.tranceError();
		}
		// 查询数据库
		BeeQueryWrapper wrapper = new BeeQueryWrapper(new SysMenu());

		final List<SysMenu> menuList = beeDBService.findManyByWrapper(wrapper);
		menuList.stream().forEach(item -> {
			item.setLabel(item.getNAME());
			item.setValue(item.getId());
		});
		final List<SysMenu> menuTree = TreeUtils.list2Tree(menuList, "0", "id", "PID", "children", false);
		//final List<OptionDTO> menuOptionTree = EntityUtil.toOptionTree(menuTree);

		// 返回结果集
		return BeeError.BEE_SUC.tranceError(menuTree);
	}


}
